<template>
    <div>
        <div class="filter">
            <el-form :inline="true" :model="formInline" ref="ruleForm">
                <el-form-item label="业主昵称" prop="nickname">
                    <el-input v-model="formInline.nickname" placeholder="请输入业主昵称"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="onSubmit">查询业主</el-button>
                    <el-button @click="resetForm('ruleForm')">重置</el-button>
                </el-form-item>
            </el-form>
        </div>
        <div class="table">
            <div class="add">
                <el-button type="primary" @click="add">新增业主信息</el-button>
            </div>
            <div class="data">
                <el-table :data="tableData" border style="width: 100%">
                    <el-table-column fixed prop="nickname" label="业主昵称" width="150">
                    </el-table-column>
                    <el-table-column prop="gender" label="性别">
                        <template slot-scope="scope">
                            <div>
                                {{scope.row.gender=='1'?'男':'女'}}
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column prop="birth" label="生日">
                        <template slot-scope="scope">
                            <div>
                                {{scope.row.birth&&scope.row.birth.split(" ")[0]}}
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column prop="phone" label="手机号">
                    </el-table-column>
                    <el-table-column fixed="right" label="添加房屋" width="100">
                        <template slot-scope="scope">
                            <el-button type="text" size="small" @click="addRoom(scope.row.id)">添加房屋</el-button>
                        </template>
                    </el-table-column>
                    <el-table-column fixed="right" label="添加车位" width="100">
                        <template slot-scope="scope">
                            <el-button type="text" size="small" @click="addStall(scope.row.id)">添加车位</el-button>
                        </template>
                    </el-table-column>
                    <el-table-column fixed="right" label="操作" width="100">
                        <template slot-scope="scope">
                            <el-button type="text" size="small" @click="getUserById(scope.row.id)">编辑</el-button>
                            <el-button @click="deleteUser(scope.row.id)" type="text" size="small">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
            <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="pageInfo.page" :page-sizes="[10, 20]" :page-size="pageInfo.size" layout="total, sizes, prev, pager, next, jumper" :total="pageInfo.total">
            </el-pagination>
        </div>
        <el-dialog :title="isAdd?'新增业主信息':'编辑业主信息'" width="600px" :visible.sync="dialogFormVisible" center>
            <el-form :model="addForm" label-width="100px" :rules="addRules" ref="addForm">
                <el-form-item label="用户头像">
                    <el-upload class="avatar-uploader" action="http://192.168.101.13:10001/api/images/upload" name="pic" :show-file-list="false" :on-success="handleAvatarSuccess">
                        <img v-if="addForm.avatar" :src="addForm.avatar" class="avatar">
                        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                    </el-upload>
                </el-form-item>
                <el-form-item label="昵称" prop="nickname">
                    <el-input v-model="addForm.nickname"></el-input>
                </el-form-item>
                <el-form-item label="密码" prop="password">
                    <el-input type='password' v-model="addForm.password"></el-input>
                </el-form-item>
                <el-form-item label="性别">
                    <el-radio-group v-model="addForm.gender">
                        <el-radio :label="1">男</el-radio>
                        <el-radio :label="0">女</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="生日" prop="birth">
                    <el-date-picker v-model="addForm.birth" type="date" placeholder="选择日期" :picker-options="pickerOptions" value-format="yyyy-MM-dd">
                    </el-date-picker>
                </el-form-item>
                <el-form-item label="手机号" prop="phone">
                    <el-input v-model="addForm.phone"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取 消</el-button>
                <el-button type="primary" @click="commitForm('addForm')">确 定</el-button>
            </div>
        </el-dialog>
        <el-dialog title="添加房屋" :visible.sync="roomVisible">
            <el-form :model="roomForm">
                <el-form-item label="已买房屋" label-width="100">
                    <div class="flex-center">
                        <el-tag v-for="item in userRoom" :key="item.id" closable @close="deleteRoom(item.id)">{{item.roomNumber}}</el-tag>
                    </div>
                </el-form-item>
                <el-form-item label="选择房屋" label-width="100">
                    <el-select v-model="roomForm.room" multiple filterable placeholder="请选择房屋">
                        <el-option v-for="item in allRoom" :key="item.id" :label="item.roomNumber" :value="item.id"></el-option>
                    </el-select>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="roomVisible = false">取 消</el-button>
                <el-button type="primary" @click="commitRoomForm">确 定</el-button>
            </div>
        </el-dialog>
        <el-dialog title="添加车位" :visible.sync="stallVisible">
            <el-form :model="stallForm">
                <el-form-item label="已买车位" label-width="100">
                    <div class="flex-center">
                        <el-tag v-for="item in userStall" :key="item.id" closable @close="deleteStall(item.id)">{{item.number}}</el-tag>
                    </div>
                </el-form-item>
                <el-form-item label="选择车位" label-width="100">
                    <el-select v-model="stallForm.stall" multiple filterable placeholder="请选择车位">
                        <el-option v-for="item in allStall" :key="item.id" :label="item.number" :value="item.id"></el-option>
                    </el-select>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="stallVisible = false">取 消</el-button>
                <el-button type="primary" @click="commitStallForm">确 定</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import api from "../../../api";
export default {
    name: "owner",
    data() {
        return {
            formInline: {
                nickname: "",
            },
            pageInfo: {
                currentPage: 1,
                pageSize: 10,
                total: 0,
            },
            dialogFormVisible: false,
            addForm: {
                avatar: "",
                nickname: "",
                password: "",
                gender: 1,
                birth: "",
                phone: "",
            },
            roomForm: {
                room: [],
            },
            roomVisible: false,
            stallForm: {
                stall: [],
            },
            stallVisible: false,
            tableData: [],
            isAdd: true,
            pickerOptions: {
                disabledDate(time) {
                    return time.getTime() > Date.now();
                },
            },
            addRules: {
                nickname: [
                    { required: true, message: "请输入昵称", trigger: "blur" },
                ],
                password: [
                    { required: true, message: "请输入密码", trigger: "blur" },
                ],
                birth: [
                    { required: true, message: "请选择生日", trigger: "blur" },
                ],
                phone: [
                    {
                        required: true,
                        message: "请输入手机号",
                        trigger: "blur",
                    },
                    {
                        pattern: /^1[3456789]\d{9}$/,
                        message: "请输入正确手机号",
                        trigger: "blur",
                    },
                ],
            },
            userRoom: [],
            allRoom: [],
            userStall: [],
            allStall: [],
            userId: "",
        };
    },
    mounted() {
        this.getUserList();
    },
    methods: {
        onSubmit() {
            this.pageInfo.currentPage = 1;
            this.getUserList();
        },
        resetForm(formName) {
            this.$refs[formName].resetFields();
        },
        handleAvatarSuccess(res, file) {
            this.addForm.avatar = res.data;
        },
        // 分页获取业主数据
        async getUserList() {
            try {
                const params = Object.assign(
                    {},
                    this.pageInfo,
                    this.formInline
                );
                const response = await api.user.getUserPage(params);
                if (response.data.code === 200) {
                    this.tableData = response.data.data.records;
                    this.pageInfo.total = response.data.data.total;
                } else {
                    this.$message.error(response.data.msg);
                }
            } catch (error) {
                this.$message.error(error);
            }
        },
        // 根据ID获取业主
        async getUserById(id) {
            this.isAdd = false;
            this.dialogFormVisible = true;
            try {
                const response = await api.user.getUserById({
                    userId: id,
                });
                if (response.data.code === 200) {
                    this.addForm = response.data.data;
                } else {
                    this.$message.error(response.data.msg);
                }
            } catch (error) {
                this.$message.error(error);
            }
        },
        // 添加或者编辑提交
        async commitForm(formName) {
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    if (this.isAdd) {
                        this.commitAddForm();
                    } else {
                        this.commitEditForm();
                    }
                    this.dialogFormVisible = false;
                    this.addForm = this.$options.data().addForm; //重置表单数据
                }
            });
        },
        // 提交添加用户
        async commitAddForm() {
            try {
                const response = await api.user.addUser(this.addForm);
                if (response.data.code === 200) {
                    this.$message.success("添加成功");
                    this.getUserList();
                } else {
                    this.$message.error(response.data.msg);
                }
            } catch (error) {
                this.$message.error(error);
            }
        },
        // 提交编辑用户
        async commitEditForm() {
            try {
                const response = await api.user.editUser(this.addForm);
                if (response.data.code === 200) {
                    this.$message.success("编辑成功");
                    this.getUserList();
                } else {
                    this.$message.error(response.data.msg);
                }
            } catch (error) {
                this.$message.error(error);
            }
        },
        // 点击新增按钮
        add() {
            this.isAdd = true;
            this.dialogFormVisible = true;
            this.addForm = this.$options.data().addForm;
        },
        // 删除业主
        deleteUser(id) {
            this.$confirm("确认删除, 是否继续?", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
            })
                .then(async () => {
                    try {
                        const response = await api.user.deleteUser({
                            userId: id,
                        });
                        if (response.data.code === 200) {
                            this.$message.success("删除成功");
                            this.getUserList();
                        } else {
                            this.$message.error(response.data.msg);
                        }
                    } catch (error) {
                        this.$message.error(error);
                    }
                })
                .catch(() => {});
        },
        /**
         * @description 添加房间
         */
        addRoom(id) {
            this.userId = id;
            this.roomVisible = true;
            this.roomForm.room = [];
            this.userRoom = [];
            this.getRoomById();
            this.getAllRoom();
        },
        /**
         * @description 获取指定房间
         */
        async getRoomById() {
            this.userRoom = [];
            try {
                const response = await api.user.getRoomByUserId({
                    UserId: this.userId,
                });
                if (response.data.code === 200) {
                    this.userRoom = response.data.data || [];
                    this.roomVisible = true;
                } else {
                    this.$message.error(response.data.msg);
                }
            } catch (error) {
                this.$message.error(error);
            }
        },
        /**
         * @description 提交房间
         */
        async commitRoomForm() {
            try {
                const response = await api.user.addRoomByUser({
                    userId: this.userId,
                    roomId: this.roomForm.room,
                });
                if (response.data.code === 200) {
                    this.roomVisible = false;
                    this.$message.success(response.data.msg);
                } else {
                    this.$message.error(response.data.msg);
                }
            } catch (error) {
                this.$message.error(error);
            }
        },
        /**
         * @description 获取所有房间
         */
        async getAllRoom() {
            try {
                const response = await api.user.getAllRoom();
                if (response.data.code === 200) {
                    this.allRoom = response.data.data || [];
                } else {
                    this.$message.error(response.data.msg);
                }
            } catch (error) {
                this.$message.error(error);
            }
        },
        /**
         * @description 删除房子
         */
        async deleteRoom(id) {
            try {
                const response = await api.user.deleteRoom({
                    userId: this.userId,
                    roomId: id,
                });
                if (response.data.code === 200) {
                    this.$message.success(response.data.msg);
                    this.getRoomById();
                } else {
                    this.$message.error(response.data.msg);
                }
            } catch (error) {
                this.$message.error(error);
            }
        },
        /**
         * @description 添加车位
         */
        addStall(id) {
            this.userId = id;
            this.stallVisible = true;
            this.stallForm.stall = [];
            this.userStall = [];
            this.getStallById();
            this.getAllStall();
        },
        /**
         * @description 获取指定车位
         */
        async getStallById() {
            this.userStall = [];
            try {
                const response = await api.user.getStallByUserId({
                    UserId: this.userId,
                });
                if (response.data.code === 200) {
                    this.userStall = response.data.data || [];
                    this.stallVisible = true;
                } else {
                    this.$message.error(response.data.msg);
                }
            } catch (error) {
                this.$message.error(error);
            }
        },
        /**
         * @description 提交车位
         */
        async commitStallForm() {
            try {
                const response = await api.user.addStallByUser({
                    userId: this.userId,
                    stallId: this.stallForm.stall,
                });
                if (response.data.code === 200) {
                    this.stallVisible = false;
                    this.$message.success(response.data.msg);
                } else {
                    this.$message.error(response.data.msg);
                }
            } catch (error) {
                this.$message.error(error);
            }
        },
        /**
         * @description 获取所有车位
         */
        async getAllStall() {
            try {
                const response = await api.user.getAllStall();
                if (response.data.code === 200) {
                    this.allStall = response.data.data || [];
                } else {
                    this.$message.error(response.data.msg);
                }
            } catch (error) {
                this.$message.error(error);
            }
        },
        /**
         * @description 删除车位
         */
        async deleteStall(id) {
            try {
                const response = await api.user.deleteStall({
                    stallId: id,
                });
                if (response.data.code === 200) {
                    this.$message.success(response.data.msg);
                    this.getStallById();
                } else {
                    this.$message.error(response.data.msg);
                }
            } catch (error) {
                this.$message.error(error);
            }
        },
        handleSizeChange(val) {
            this.pageInfo.size = val;
            this.getUserList();
        },
        handleCurrentChange(val) {
            this.pageInfo.currentPage = val;
            this.getUserList();
        },
    },
};
</script>

<style lang='less' scoped>
.flex-center {
    display: flex;
    align-items: center;
    height: 100%;
    .el-tag {
        margin-right: 10px;
    }
}
</style>